<!--
 * @Author: your name
 * @Date: 2021-06-01 10:32:30
 * @LastEditTime: 2021-06-06 21:38:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \遵义报名\zunyi\src\views\signUpList\signUpList.vue
-->
<template>
  <div class="signUp">
    <!-- 导航条 -->
    <nav-bar></nav-bar>

    <div class="container">
      <!-- 考试基本信息 -->
      <div class="examInfo">
        <p>考试名称：{{ examDetails.name }}</p>
        <p>考试期数：{{ examDetails.podl }}</p>
        <p>考试时间：{{ examDetails.emtm }}</p>
        <p>主办单位：{{ examDetails.ogze }}</p>
        <p>考试费用：{{ examDetails.cost }}</p>
      </div>

      <!-- 公共表单 -->
      <el-form-item>
        
      </el-form-item>
      <div v-for="item of publicForm" :key="item.id">
        <!-- 输入框 -->
        <template v-if="item.type === 1">
          <span>{{ item.ndsib }}</span>
          <myinput v-model="item.value"></myinput>
        </template>

        <!-- 单选框 -->
        <template v-if="item.type === 2">
          <span>{{ item.ndsib }}</span>
          <my-radio :valueArray="item.options" v-model="item.value"></my-radio>
        </template>

        <!-- 多选框 -->
        <template v-if="item.type === 3">
          <span>{{ item.ndsib }}</span>
          <more-radio
            :valueArray="item.options"
            v-model="item.value"
          ></more-radio>
        </template>

        <!-- 下拉列表 -->
        <template v-if="item.type === 4">
          <span>{{ item.ndsib }}</span>
          <my-select
            :valueArray="item.options"
            v-model="item.value"
          ></my-select>
        </template>

        <!-- 上传文件 -->
        <template v-if="item.type === 4">
          <span>{{ item.ndsib }}</span>
          <my-select
            :valueArray="item.options"
            v-model="item.value"
          ></my-select>
        </template>

         <!-- 日期 -->
        <template v-if="item.type === 4">
          <span>{{ item.ndsib }}</span>
          <my-select
            :valueArray="item.options"
            v-model="item.value"
          ></my-select>
        </template>

         <!-- 多行文本 -->
        <template v-if="item.type === 6">
          <span>{{ item.ndsib }}</span>
          <my-select
            :valueArray="item.options"
            v-model="item.value"
          ></my-select>
        </template>
      </div>

      <hr />

      <!-- 特殊表单 -->
      <div v-for="item of specialForm" :key="item.id">
        <!-- 输入框 -->
        <template v-if="item.type === 1">
          <span>{{ item.ndsib }}</span>
          <myinput v-model="item.value"></myinput>
        </template>

        <!-- 单选框 -->
        <template v-if="item.type === 2">
          <span>{{ item.ndsib }}</span>
          <my-radio :valueArray="item.options" v-model="item.value"></my-radio>
        </template>

        <!-- 多选框 -->
        <template v-if="item.type === 3">
          <span>{{ item.ndsib }}</span>
          <more-radio
            :valueArray="item.options"
            v-model="item.value"
          ></more-radio>
        </template>

        <!-- 下拉列表 -->
        <template v-if="item.type === 4">
          <span>{{ item.ndsib }}</span>
          <my-select
            :valueArray="item.options"
            v-model="item.value"
          ></my-select>
        </template>

        <!-- 弹窗 -->
        <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">

        </el-dialog>

        <span>请填写：</span>
        <span v-for="(item,idx) of validatorArray" :key="item.id">
          {{idx === 0 ? '' : '、'}}
          {{item.ndsib}}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { getFromUrl } from "api/examList.js";
import { url } from "api/sendCode.js";
import { saveUrl } from "api/examList.js";
import { updateUrl } from "api/userInfo.js";

import { createNamespacedHelpers } from "vuex";
const { mapState, mapMutations } = createNamespacedHelpers("userInfo");

export default {
  props: {
    eid: {
      //考试id
      type: String,
      required: true,
    },
    data: {
      //考试信息
      type: String,
      required: true,
    },
  },
  data() {
    return {
      examDetails: "", //考试详情信息
      examFormInfo: "", //提交给后端的数据结构
      publicForm: "", //公共表单
      specialForm: "", //特殊表单
      form: {}, //表单绑定数据
      dialogVisible: false, //校验弹窗
      codeDialogVisible: false, //短信弹窗
      validatorArray: [], //校验数组
      time: 5, //倒计时时间
      showTime: false, //显示倒计时
      codeForm: {
        //短信表单
        code: "",
      },
      codeFormRules: {
        //短信校验
        code: [
          { required: true, message: "请输入短信验证码", trigger: "blur" },
        ],
      },
      submitLoading: false, //提交loading
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  methods: {
    ...mapMutations(["updateUserInfo"]),
    API_getFrom(eid) {
      //获取表格接口
      return this.$httpRequest({
        url: getFromUrl,
        method: "POST",
        data: {
          param: {
            eid,
          },
        },
      });
    },
    API_sendCode() {
      //发送验证码接口
      return this.$httpRequest({
        url: url,
        method: "POST",
        data: {},
      });
    },
    API_save(data, code) {
      //报考接口
      return this.$httpRequest({
        url: saveUrl,
        method: "POST",
        data: {
          data: data,
          param: {
            code: code,
          },
        },
      });
    },
    API_update(data) {
      return this.$httpRequest({
        url: updateUrl,
        method: "POST",
        data: {
          data,
        },
      });
    },
    setFormVal(formArray) {
      //给公共表单、特殊表单都添加一个value值，用来做值
      formArray.forEach((item) => {
        if (item.type !== 3) {
          //不是多选
          item.value = "";
        } else {
          //多选
          item.value = [];
        }
      });
    },
    setFormOptions(formArray) {
      //给公共表单、特殊表单都添加一个options值，用来做选项
      formArray.forEach((item) => {
        if (item.type === 2 || item.type === 3) {
          //单选、多选
          let arr = item.optn.split(",");
          item.options = [];
          arr.forEach((items, idx) => {
            let arrs = items.split("-");
            item.options[idx] = { label: Number(arrs[0]), content: arrs[1] };
          });
        } else if (item.type === 4) {
          //下拉列表
          let arr = item.optn.split(",");
          item.options = [];
          arr.forEach((items, idx) => {
            let arrs = items.split("-");
            item.options[idx] = { value: arrs[0], label: arrs[1] };
          });
        }
      });
    },
    showDialog() {
      //显示弹窗

      let bool = this.form.every((item) => {
        return item.value;
      });
      if (!bool) {
        //弹校验窗
        this.validatorArray = this.form.filter((item) => {
          return !item.value;
        });
        this.dialogVisible = true;
      } else {
        //弹短信验证窗
        this.codeDialogVisible = true;
      }
    },
    async sendCode() {
      //发送验证码
      let res = await this.API_sendCode();
      if (res.data.code === 1000) {
        this.$message.success(res.data.msg);
      } else {
        this.$message.error(res.data.msg);
      }

      this.showTime = true;
      let timeHandler = setInterval(() => {
        if (this.time <= 0) {
          clearInterval(timeHandler);
          this.showTime = false;
          this.time = 5;
        } else {
          this.time--;
        }
      }, 1000);
    },
    submit(formName) {
      //提交表单
      this.submitLoading = true;
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let userInfo = JSON.parse(JSON.stringify(this.userInfo)); //用户信息
          let examDetails = JSON.parse(JSON.stringify(this.examDetails)); //考试详细信息
          let eid = this.eid; //考试id
          let emid = userInfo.id; //用户id
          userInfo.emid = emid;
          delete userInfo.id;
          delete examDetails.id;

          let data = Object.assign({}, examDetails, userInfo, {
            //合并对象
            eid: eid,
            form: this.form,
          });

          this.publicForm.forEach((item) => {
            for (let key in userInfo) {
              if (key === item.name) {
                userInfo[key] = item.value;
              }
            }
          });

          let resUserInfo = await this.API_update(userInfo); //更新用户信息
          if (resUserInfo.data.code === 1000) {
            this.updateUserInfo(userInfo);
            this.$message.success(resUserInfo.data.msg);
          } else {
            this.$message.error(resUserInfo.data.msg);
          }

          let res = await this.API_save(data, this.codeForm.code); //提交表单
          if (res.data.code === 1000) {
            this.$message.success(res.data.msg);
            this.$router.replace("/signUpList");
          } else {
            this.$message.error(res.data.msg);
          }
          this.submitLoading = false;
          this.codeDialogVisible = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  async created() {
    this.examDetails = JSON.parse(decodeURIComponent(this.data)); //获取考试信息

    let formRes = await this.API_getFrom(this.eid); //获取考试表格
    this.examFormInfo = formRes.data.data; //提交给后端的数据结构
    this.form = JSON.parse(this.examFormInfo.form); //表单数据

    this.publicForm = this.form.filter((item) => {
      //过滤出公共表单
      return item.ispublic === 1;
    });

    this.specialForm = this.form.filter((item) => {
      //过滤出特殊表单
      return item.ispublic === 0;
    });

    //给公共表单和特殊表单都添加value字段和options字段
    this.setFormVal(this.publicForm);
    this.setFormOptions(this.publicForm);

    this.setFormVal(this.specialForm);
    this.setFormOptions(this.specialForm);

    // 用户信息和公共表单进行比对，然后赋值
    this.publicForm.forEach((item) => {
      if (this.userInfo[item.name]) {
        item.value = this.userInfo[item.name];
      }
    });
  },
};
</script>

<style lang="scss" scoped>
.signUp {
  .container {
    padding: 40px;
    box-sizing: border-box;
    .examInfo {
      padding: 0 40px;
      box-sizing: border-box;

      p {
        vertical-align: middle;
        font-size: 20px;
        color: #606266;
        line-height: 40px;
        padding: 0 12px 0 0;
        box-sizing: border-box;
      }
    }
  }
}
</style>